package com.slz.crm.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slz.crm.common.exiception.BaseException;
import com.slz.crm.common.untils.BaseUnit;
import com.slz.crm.pojo.dto.SalesStageApprovalDTO;
import com.slz.crm.pojo.entity.SalesOpportunityEntity;
import com.slz.crm.pojo.entity.SalesStageApprovalEntity;
import com.slz.crm.pojo.entity.UserEntity;
import com.slz.crm.pojo.vo.AddSalesStageApprovalDTO;
import com.slz.crm.pojo.vo.SalesStageApprovalVO;
import com.slz.crm.server.annotation.Privacy;
import com.slz.crm.server.constant.MessageConstant;
import com.slz.crm.server.mapper.ApprovalAttachmentMapper;
import com.slz.crm.server.mapper.SalesOpportunityMapper;
import com.slz.crm.server.mapper.SalesStageApprovalMapper;
import com.slz.crm.server.mapper.UserMapper;
import com.slz.crm.server.service.SalesStageApprovalService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SalesStageApprovalServiceImpl extends ServiceImpl<SalesStageApprovalMapper, SalesStageApprovalEntity> implements SalesStageApprovalService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ApprovalAttachmentMapper approvalAttachmentMapper;

    @Autowired
    private SalesOpportunityMapper salesOpportunityMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SalesStageApprovalVO approveStage(AddSalesStageApprovalDTO dto) {

        SalesOpportunityEntity selected = salesOpportunityMapper.selectById(dto.getOpportunityId());

        //插入审批记录
        SalesStageApprovalEntity entity = new SalesStageApprovalEntity();
        BeanUtils.copyProperties(dto, entity);
        entity.setApplicantId(BaseUnit.getCurrentId());

        entity.setApplicantId(BaseUnit.getCurrentId());
        entity.setTargetStage(dto.getTargetStage());
        entity.setCurrentStage(selected.getStage());
        entity.setApprovalStatus(0);
        entity.setApplyTime(LocalDateTime.now());

        save(entity);

        SalesStageApprovalVO vo = new SalesStageApprovalVO();
        BeanUtils.copyProperties(entity, vo);

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(SalesStageApprovalDTO dto) {

        SalesStageApprovalEntity entity = new SalesStageApprovalEntity();
        BeanUtils.copyProperties(dto, entity);
        entity.setApprovalTime(LocalDateTime.now());
        entity.setApproverId(BaseUnit.getCurrentId());
        entity.setApprovalStatus(dto.getApprovalStatus().getFirst());
        if (entity.getApprovalStatus() == 1) {
            SalesStageApprovalEntity salesStageApprovalEntity = baseMapper.selectById(entity.getId());
            if (salesStageApprovalEntity == null) {
                throw new BaseException(MessageConstant.SALES_STAGE_APPROVAL_ID_IS_NULL);
            }
            //如果是同意，更新销售机会的阶段
            SalesOpportunityEntity opportunityEntity = salesOpportunityMapper.selectById(salesStageApprovalEntity.getOpportunityId());

            if (opportunityEntity == null) {
                throw new BaseException(MessageConstant.SALES_OPPORTUNITY_ALREADY_NULL);
            }

            opportunityEntity.setStage(salesStageApprovalEntity.getTargetStage());
            salesOpportunityMapper.updateById(opportunityEntity);
        }

        baseMapper.updateById(entity);
        return true;
    }


    @Override
    public void removeByIds(List<Long> ids) {
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    @Privacy
    public Page<SalesStageApprovalVO> getPage(Page<SalesStageApprovalEntity> page, SalesStageApprovalDTO dto) {

        LambdaQueryWrapper<SalesStageApprovalEntity> queryWrapper = Wrappers.lambdaQuery(SalesStageApprovalEntity.class);

        //通过审批人、关联销售机会名称获得相应ids
        if (dto != null) {
            //通过关联销售机会名称获得相应ids
            if (dto.getOpportunityName() != null && !dto.getOpportunityName().isEmpty()) {
                List<Long> opportunityIds = salesOpportunityMapper.selectObjs(Wrappers.lambdaQuery(SalesOpportunityEntity.class)
                        .like(SalesOpportunityEntity::getOpportunityName, dto.getOpportunityName()));

                if (!opportunityIds.isEmpty()) {
                    queryWrapper.in(SalesStageApprovalEntity::getOpportunityId, opportunityIds);
                }
            }
            //通过审批人姓名获得相应ids
            if (dto.getApproverName() != null && !dto.getApproverName().isEmpty()) {
                List<Long> approverIds = userMapper.selectObjs(Wrappers.lambdaQuery(UserEntity.class)
                        .like(UserEntity::getRealName, dto.getApproverName()));

                if (!approverIds.isEmpty()) {
                    queryWrapper.in(SalesStageApprovalEntity::getApproverId, approverIds);
                }
            }

            if (dto.getApproverId() != null) {
                queryWrapper.eq(SalesStageApprovalEntity::getApproverId, dto.getApproverId());
            }
            if (dto.getTargetStage() != null) {
                queryWrapper.like(SalesStageApprovalEntity::getTargetStage, dto.getTargetStage());
            }
            if (dto.getApprovalOpinion() != null) {
                queryWrapper.like(SalesStageApprovalEntity::getApprovalOpinion, dto.getApprovalOpinion());
            }

            if (dto.getApplyTime() != null) {
                queryWrapper.like(SalesStageApprovalEntity::getApplyTime, dto.getApplyTime());
            }
            if(dto.getApprovalStatus() != null && !dto.getApprovalStatus().isEmpty()){
                queryWrapper.in(SalesStageApprovalEntity::getApprovalStatus,dto.getApprovalStatus());
            }
        }

        Page<SalesStageApprovalEntity> pageResult = baseMapper.selectPage(page, queryWrapper);

        List<SalesStageApprovalVO> voList = pageResult.getRecords().stream().map(entity -> {
            String opportunityName = null;
            String currentStage = null;
            String targetStage = null;

            // 获取销售机会名称
            if (entity.getOpportunityId() != null) {
                SalesOpportunityEntity opportunity = salesOpportunityMapper.selectById(entity.getOpportunityId());
                if (opportunity != null) {
                    opportunityName = opportunity.getOpportunityName();
                    // 将数字阶段转换为对应的中文名称
                    currentStage = convertStageToChinese(opportunity.getStage());
                }
            }

            // 将目标阶段数字转换为对应的中文名称
            targetStage = convertStageToChinese(entity.getTargetStage());


            return SalesStageApprovalVO.fromEntity(entity,opportunityName,currentStage,targetStage);
        }).collect(Collectors.toList());

        Page<SalesStageApprovalVO> resultPage = new Page<>();
        BeanUtils.copyProperties(pageResult, resultPage);
        resultPage.setRecords(voList);

        return resultPage;
    }

    /**
     * 将销售阶段数字转换为对应的中文名称
     * @param stage 阶段数字
     * @return 中文名称
     */
    private String convertStageToChinese(Integer stage) {
        if (stage == null) {
            return null;
        }
        switch (stage) {
            case 0:
                return "初步接触";
            case 1:
                return "需求确认";
            case 2:
                return "方案提供";
            case 3:
                return "商务谈判";
            case 4:
                return "合同签订";
            case 5:
                return "已关闭";
            default:
                return "未知阶段";
        }
    }
}
